import { coordinateData } from '@/components/echart/data/coordinate'
// @ts-ignore
import SparkMd5 from 'spark-md5'

let MyStorage = {
  /**
   *
   * @param key 设置本地存储的名字
   * @param value 保存的值
   */
  set(key: string, value: any) {
    localStorage.setItem(
      key,
      JSON.stringify({
        value,
        time: new Date()
      })
    )
  },
  get(key: string, cycle: number = 3600000) {
    if (!key) return
    if (isNaN(cycle)) cycle = 3600000
    let data = localStorage.getItem(key)
    if (!data) return
    let { time, value } = JSON.parse(data)
    if (+new Date() - time >= cycle) {
      // 当前时间-保存数据的时间超过设置时间则删除本地数据
      MyStorage.remove(key)
      return
    }
    return value
  },
  remove(key: string) {
    localStorage.removeItem(key)
  }
}

// 根据城市名字配合经纬度信息，绘制
function convertData(data: any) {
  const res = []
  for (let i = 0; i < data.length; i++) {
    const geoCoord = coordinateData[data[i].name]
    if (geoCoord) {
      res.push({
        name: data[i].name,
        value: geoCoord.concat(data[i].value)
      })
    }
  }
  return res
}

// 生成文件名
function createBufferHashName(file: any) {
  return new Promise((resolve, reject) => {
    let reader = new FileReader()
    reader.readAsArrayBuffer(file)
    reader.onload = (res) => {
      let buffer = res.target?.result //二进制文件信息，文件名需要
      let spark = new SparkMd5.ArrayBuffer()
      spark.append(buffer)
      let hash = spark.end()
      let suffiex = file.name.split('.')[1]

      resolve({
        hash,
        suffiex,
        filename: `${hash}.${suffiex}`
      })
    }
  })
}
export { MyStorage, convertData, createBufferHashName }
